@extends('backend.layouts.app')

@section('content')
    <?php

    $show_index = @file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/showindex.txt');
    $show_index = intval($show_index);

    ?>
    <div class="aiz-titlebar text-left mt-2 mb-3">
        <div class="row align-items-center">
            <div class="col-auto">
                <h1 class="h3">{{translate('All products')}}</h1>
            </div>
            @if($type != 'Seller')
                <div class="col text-right">
                    <a href="{{ route('products.create') }}" class="btn btn-circle btn-info">
                        <span>{{translate('Add New Product')}}</span>
                    </a>
                </div>
            @endif
        </div>
    </div>
    <br>

    <div class="card">
        <form class="" id="sort_products" action="" method="GET">
            <div class="card-header row gutters-5">
                <div class="col">
                    <h5 class="mb-md-0 h6">{{ translate('All Product') }}</h5>

                    <label class="aiz-switch aiz-switch-success mb-0">
                        <input onchange="update_approved2(this)" value="1"
                               type="checkbox" <?php if ($show_index == 1) echo "checked"; ?> >
                        <span class="slider round"></span>
                    </label>
                    首页展示产品库商品


                </div>

                <div class="dropdown mb-2 mb-md-0">
                    <button class="btn border dropdown-toggle" type="button" data-toggle="dropdown">
                        {{translate('Bulk Action')}}
                    </button>


                    <div class="dropdown-menu dropdown-menu-right">
                        <a class="dropdown-item" href="#" onclick="bulk_sales()">{{translate('Set Virtual Sales')}}</a>
                        <a class="dropdown-item" href="#" onclick="bulk_rating()">{{translate('Set Virtual Rating')}}</a>
                        <a class="dropdown-item" href="#" onclick="bulk_delete()"> {{translate('Delete selection')}}</a>
                        <a class="dropdown-item" href="#" onclick="bulk_export()"> 导出</a>
                    </div>
                </div>

                @if($type == 'Seller')
                    <div class="col-md-2 ml-auto">
                        <select class="form-control form-control-sm aiz-selectpicker mb-2 mb-md-0" id="user_id"
                                name="user_id" onchange="sort_products()">
                            <option value="">{{ translate('All Sellers') }}</option>
                            @foreach (App\Models\Seller::all() as $key => $seller)
                                @if ($seller->user != null && $seller->user->shop != null)
                                    <option value="{{ $seller->user->id }}"
                                            @if ($seller->user->id == $seller_id) selected @endif>{{ $seller->user->shop->name }}
                                        ({{ $seller->user->name }})
                                    </option>
                                @endif
                            @endforeach
                        </select>
                    </div>
                @endif
                @if($type == 'All')
                    <div class="col-md-2 ml-auto">
                        <select class="form-control form-control-sm aiz-selectpicker mb-2 mb-md-0" id="user_id"
                                name="user_id" onchange="sort_products()">
                            <option value="">{{ translate('All Sellers') }}</option>
                            @foreach (App\Models\User::where('user_type', '=', 'admin')->orWhere('user_type', '=', 'seller')->get() as $key => $seller)
                                <option value="{{ $seller->id }}"
                                        @if ($seller->id == $seller_id) selected @endif>{{ $seller->name }}</option>
                            @endforeach
                        </select>
                    </div>
                @endif
                <div class="col-md-2 ml-auto">
                    <select class="form-control form-control-sm aiz-selectpicker mb-2 mb-md-0" name="type" id="type"
                            onchange="sort_products()">
                        <option value="">{{ translate('Sort By') }}</option>
                        <option value="rating,desc"
                                @isset($col_name , $query) @if($col_name == 'rating' && $query == 'desc') selected @endif @endisset>{{translate('Rating (High > Low)')}}</option>
                        <option value="rating,asc"
                                @isset($col_name , $query) @if($col_name == 'rating' && $query == 'asc') selected @endif @endisset>{{translate('Rating (Low > High)')}}</option>
                        <option value="num_of_sale,desc"
                                @isset($col_name , $query) @if($col_name == 'num_of_sale' && $query == 'desc') selected @endif @endisset>{{translate('Num of Sale (High > Low)')}}</option>
                        <option value="num_of_sale,asc"
                                @isset($col_name , $query) @if($col_name == 'num_of_sale' && $query == 'asc') selected @endif @endisset>{{translate('Num of Sale (Low > High)')}}</option>
                        <option value="unit_price,desc"
                                @isset($col_name , $query) @if($col_name == 'unit_price' && $query == 'desc') selected @endif @endisset>{{translate('Base Price (High > Low)')}}</option>
                        <option value="unit_price,asc"
                                @isset($col_name , $query) @if($col_name == 'unit_price' && $query == 'asc') selected @endif @endisset>{{translate('Base Price (Low > High)')}}</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <div class="form-group mb-0">
                        <input type="text" class="form-control form-control-sm" id="search" name="search"
                               @isset($sort_search) value="{{ $sort_search }}"
                               @endisset placeholder="{{ translate('Type & Enter') }}">
                    </div>
                </div>
            </div>

            <div class="card-body">
                <table class="table aiz-table mb-0">
                    <thead>
                    <tr>
                        <th>
                            <div class="form-group">
                                <div class="aiz-checkbox-inline">
                                    <label class="aiz-checkbox">
                                        <input type="checkbox" class="check-all">
                                        <span class="aiz-square-check"></span>
                                    </label>
                                </div>
                            </div>
                        </th>
                        <!--<th data-breakpoints="lg">#</th>-->
                        <th>{{translate('Name')}}</th>
                        @if($type == 'Seller' || $type == 'All')
                            <th data-breakpoints="lg">{{translate('Added By')}}</th>
                        @endif
                        <th data-breakpoints="sm">{{translate('Info')}}</th>
                        <th data-breakpoints="md">{{translate('Total Stock')}}</th>
                        <th data-breakpoints="lg">{{translate('Todays Deal')}}</th>
                        <th data-breakpoints="lg">{{translate('Published')}}</th>
                        @if(get_setting('product_approve_by_admin') == 1 && $type == 'Seller')
                            <th data-breakpoints="lg">{{translate('Approved')}}</th>
                        @endif
                        <th data-breakpoints="lg">{{translate('Featured')}}</th>
                        @if( $cpk == 0)
                            <th data-breakpoints="lg">发布到产品库</th>
                        @endif
                        <th data-breakpoints="sm" class="text-right">{{translate('Options')}}</th>
                    </tr>
                    </thead>
                    <tbody>
                    @foreach($products as $key => $product)
                        <tr>
                        <!--<td>{{ ($key+1) + ($products->currentPage() - 1)*$products->perPage() }}</td>-->
                            <td>
                                <div class="form-group d-inline-block">
                                    <label class="aiz-checkbox">
                                        <input type="checkbox" class="check-one" name="id[]" value="{{$product->id}}">
                                        <span class="aiz-square-check"></span>
                                    </label>
                                </div>
                            </td>
                            <td>
                                <div class="row gutters-5 w-200px w-md-300px mw-100">
                                    <div class="col-auto">
                                        <img src="{{ uploaded_asset($product->thumbnail_img)}}" alt="Image"
                                             class="size-50px img-fit">
                                    </div>
                                    <div class="col">
                                        <span class="text-muted text-truncate-2">{{ $product->getTranslation('name') }}</span>
                                    </div>
                                </div>
                            </td>
                            @if($type == 'Seller' || $type == 'All')
                                <td>{{ $product->user->name }}</td>
                            @endif
                            <td>
                                <strong>{{translate('Num of Sale')}}
                                    :</strong> {{ $product->num_of_sale }} {{translate('times')}} </br>
                                <strong>{{translate('Unit Price')}}
                                    :</strong> {{ single_price($product->unit_price) }} </br>
                                <strong>{{translate('Purchasing Price')}}
                                    :</strong> {{ single_price($product->purchase_price) }} </br>
                                <strong>{{translate('Rating')}}:</strong> {{ $product->rating }} </br>
                            </td>
                            <td>
                                @php
                                    $qty = 0;
                                    if($product->variant_product) {
                                        foreach ($product->stocks as $key => $stock) {
                                            $qty += $stock->qty;
                                            echo $stock->variant.' - '.$stock->qty.'<br>';
                                        }
                                    }
                                    else {
                                        //$qty = $product->current_stock;
                                        $qty = 10000;;
                                        echo $qty;
                                    }
                                @endphp
                                @if($qty <= $product->low_stock_quantity)
                                    <span class="badge badge-inline badge-danger">Low</span>
                                @endif
                            </td>
                            <td>
                                <label class="aiz-switch aiz-switch-success mb-0">
                                    <input onchange="update_todays_deal(this)" value="{{ $product->id }}"
                                           type="checkbox" <?php if ($product->todays_deal == 1) echo "checked"; ?> >
                                    <span class="slider round"></span>
                                </label>
                            </td>
                            <td>
                                <label class="aiz-switch aiz-switch-success mb-0">
                                    <input onchange="update_published(this)" value="{{ $product->id }}"
                                           type="checkbox" <?php if ($product->published == 1) echo "checked"; ?> >
                                    <span class="slider round"></span>
                                </label>
                            </td>
                            @if(get_setting('product_approve_by_admin') == 1 && $type == 'Seller')
                                <td>
                                    <label class="aiz-switch aiz-switch-success mb-0">
                                        <input onchange="update_approved(this)" value="{{ $product->id }}"
                                               type="checkbox" <?php if ($product->approved == 1) echo "checked"; ?> >
                                        <span class="slider round"></span>
                                    </label>
                                </td>
                            @endif
                            <td>
                                <label class="aiz-switch aiz-switch-success mb-0">
                                    <input onchange="update_featured(this)" value="{{ $product->id }}"
                                           type="checkbox" <?php if ($product->featured == 1) echo "checked"; ?> >
                                    <span class="slider round"></span>
                                </label>
                            </td>
                            @if( $cpk == 0)



                                <td>
                                    <?php if ($product->cpk == 0 ){ ?>

                                    <a class="btn  btn-sm"
                                       style="width:90px; font-size:12px;background:#D20000; color:#FFF; padding:5px 0px;"
                                       href="{{route('products.duplicate', ['id'=>$product->id, 'type'=>'cpk']  )}}"
                                       title="发布到产品库">
                                        发布到产品库
                                    </a>
                                    <?php } else {
                                        echo " <font color='#D20000'>已发布到产品库</font>"; ?>
                               <?php } ?>
                                </td>
                            @endif

                            <td class="text-right">
                                <a class="btn btn-soft-success btn-icon btn-circle btn-sm"
                                   href="{{ route('product', $product->slug) }}" target="_blank"
                                   title="{{ translate('View') }}">
                                    <i class="las la-eye"></i>
                                </a>
                                @if ($type == 'Seller')
                                    <a class="btn btn-soft-primary btn-icon btn-circle btn-sm"
                                       href="{{route('products.seller.edit', ['id'=>$product->id, 'lang'=>env('DEFAULT_LANGUAGE')] )}}"
                                       title="{{ translate('Edit') }}">
                                        <i class="las la-edit"></i>
                                    </a>
                                @else
                                    <a class="btn btn-soft-primary btn-icon btn-circle btn-sm"
                                       href="{{route('products.admin.edit', ['id'=>$product->id, 'lang'=>env('DEFAULT_LANGUAGE')] )}}"
                                       title="{{ translate('Edit') }}">
                                        <i class="las la-edit"></i>
                                    </a>
                                @endif
                                @if( $cpk == 0 )
                                    <a class="btn btn-soft-warning btn-icon btn-circle btn-sm"
                                       href="{{route('products.duplicate', ['id'=>$product->id, 'type'=>$type]  )}}"
                                       title="{{ translate('Duplicate') }}">
                                        <i class="las la-copy"></i>
                                    </a>
                                @endif

                                @if( $cpk == 1)
                                    <a class="btn btn-soft-warning btn-icon btn-circle btn-sm"
                                       href="{{route('products.duplicate', ['id'=>$product->id, 'type'=>'yccpk']  )}}"
                                       title="移出产品库">
                                        <i class="las la-trash"></i>
                                    </a>
                                @else
                                    <a href="#" class="btn btn-soft-danger btn-icon btn-circle btn-sm confirm-delete"
                                       data-href="{{route('products.destroy', $product->id)}}"
                                       title="{{ translate('Delete') }}">
                                        <i class="las la-trash"></i>
                                    </a>
                                @endif


                            </td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
                <div class="aiz-pagination">
                    {{ $products->appends(request()->input())->links() }}
                </div>
            </div>
        </form>
    </div>

    <div class="modal fade" id="virtual_sales_form" data-backdrop="static">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title h6">{{translate('Bulk Set Sales')}}</h5>
                    <button type="button" class="close" data-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" method="POST">

                        <div class="form-group row">
                            <div class="col-lg-3">{{translate('Virtual Min Sales')}}</div>
                            <div class="col-lg-6">
                                <input type="number" min="1" step="1" class="form-control" name="min_sales" value="1"
                                       placeholder="" required>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col-lg-3">{{translate('Virtual Max Sales')}}</div>
                            <div class="col-lg-6">
                                <input type="number" min="1" step="1" class="form-control" name="max_sales" value="1"
                                       placeholder="" required>
                            </div>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-dismiss="modal">{{translate('Cancel')}}</button>
                    <a type="button" id="submitVirtualSales" class="btn btn-primary">{{translate('Submit')}}</a>
                </div>
            </div>
        </div>
    </div>


    <div class="modal fade" id="virtual_rating_form" data-backdrop="static">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title h6">{{translate('Bulk Set Rating')}}</h5>
                    <button type="button" class="close" data-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" action="" method="POST">

                        <div class="form-group row">
                            <div class="col-lg-3">{{translate('Virtual Rating')}}</div>
                            <div class="col-lg-6">
                                <input type="text" class="form-control" name="rating" value="5"
                                       placeholder="" required>
                            </div>
                        </div>


                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-dismiss="modal">{{translate('Cancel')}}</button>
                    <a type="button" id="submitVirtualRating" class="btn btn-primary">{{translate('Submit')}}</a>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('modal')
    @include('modals.delete_modal')
@endsection


@section('script')
    <script type="text/javascript">

        $(document).on("change", ".check-all", function () {
            if (this.checked) {
                // Iterate each checkbox
                $('.check-one:checkbox').each(function () {
                    this.checked = true;
                });
            } else {
                $('.check-one:checkbox').each(function () {
                    this.checked = false;
                });
            }

        });

        $(document).ready(function () {
            //$('#container').removeClass('mainnav-lg').addClass('mainnav-sm');
        });

        function update_todays_deal(el) {
            if (el.checked) {
                var status = 1;
            } else {
                var status = 0;
            }
            $.post('{{ route('products.todays_deal') }}', {
                _token: '{{ csrf_token() }}',
                id: el.value,
                status: status
            }, function (data) {
                if (data == 1) {
                    AIZ.plugins.notify('success', '{{ translate('Todays Deal updated successfully') }}');
                } else {
                    AIZ.plugins.notify('danger', '{{ translate('Something went wrong') }}');
                }
            });
        }

        function update_published(el) {
            if (el.checked) {
                var status = 1;
            } else {
                var status = 0;
            }
            $.post('{{ route('products.published') }}', {
                _token: '{{ csrf_token() }}',
                id: el.value,
                status: status
            }, function (data) {
                if (data == 1) {
                    AIZ.plugins.notify('success', '{{ translate('Published products updated successfully') }}');
                } else {
                    AIZ.plugins.notify('danger', '{{ translate('Something went wrong') }}');
                }
            });
        }

        function update_approved(el) {
            if (el.checked) {
                var approved = 1;
            } else {
                var approved = 0;
            }
            $.post('{{ route('products.approved') }}', {
                _token: '{{ csrf_token() }}',
                id: el.value,
                approved: approved
            }, function (data) {
                if (data == 1) {
                    AIZ.plugins.notify('success', '{{ translate('Product approval update successfully') }}');
                } else {
                    AIZ.plugins.notify('danger', '{{ translate('Something went wrong') }}');
                }
            });
        }

        function update_approved2(el) {
            if (el.checked) {
                var approved = 1;
            } else {
                var approved = 0;
            }
            $.post('{{ route('products.approved2') }}', {
                _token: '{{ csrf_token() }}',
                id: el.value,
                approved: approved
            }, function (data) {
                if (data == 1) {
                    AIZ.plugins.notify('success', '{{ translate('  update successfully') }}');
                } else {
                    AIZ.plugins.notify('danger', '{{ translate('Something went wrong') }}');
                }
            });
        }


        function update_featured(el) {
            if (el.checked) {
                var status = 1;
            } else {
                var status = 0;
            }
            $.post('{{ route('products.featured') }}', {
                _token: '{{ csrf_token() }}',
                id: el.value,
                status: status
            }, function (data) {
                if (data == 1) {
                    AIZ.plugins.notify('success', '{{ translate('Featured products updated successfully') }}');
                } else {
                    AIZ.plugins.notify('danger', '{{ translate('Something went wrong') }}');
                }
            });
        }

        function sort_products(el) {
            $('#sort_products').submit();
        }

        function bulk_delete() {
            var data = new FormData($('#sort_products')[0]);
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: "{{route('bulk-product-delete')}}",
                type: 'POST',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    if (response == 1) {
                        location.reload();
                    }
                }
            });
        }


        function bulk_export() {

            var pvalue = '';
            $("input[name='id[]']").each(function (i) {
                if (this.checked) {
                    pvalue += $(this).val() + ",";
                }
            });
            if (pvalue == '') {
                alert('请选择要导出的商品');
                return false;
            }
            location.href = '/product-bulk-export?ids=' + pvalue;
            return true;

            var data = new FormData($('#sort_products')[0]);
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: "{{route('product_bulk_export.index')}}",
                type: 'POST',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    if (response == 1) {
                        location.reload();
                    }
                }
            });
        }

        function bulk_sales()
        {
            $('#virtual_sales_form').modal('show')

        }

        $('#submitVirtualSales').bind('click', function() {
            let id_list = $("input[name='id[]']:checked")
            let ids = []
            id_list.each(function () {
                ids.push($(this).attr('value'))
            });
            let target = $(this)
            if (target.hasClass('disabled')) return false

            target.addClass('disabled');

            let min = $('input[name="min_sales"]').val()
            let max = $('input[name="max_sales"]').val()

            fetch('{{route('products.bulk_set_sales')}}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'fetch'
                },
                body: JSON.stringify({
                    _token: '{{csrf_token()}}',
                    min,
                    max,
                    ids: ids.join(',')
                })
            })
                .then(resp => resp.text())
                .then(res => {
                    if (res == 1) {
                        AIZ.plugins.notify('success', '{{translate('Operation Success')}}')
                        setTimeout(() => {
                            window.location.reload()
                        }, 500)
                    } else {
                        AIZ.plugins.notify('danger', '{{translate('Operation Fail')}}')
                        target.removeClass('disabled')
                    }

                })
                .catch(err => null).finally(() => {
                //target.removeClass('disabled')
            })

        })


        function bulk_rating()
        {
            $('#virtual_rating_form').modal('show')

        }

        $('#submitVirtualRating').bind('click', function() {
            let id_list = $("input[name='id[]']:checked")
            let ids = []
            id_list.each(function () {
                ids.push($(this).attr('value'))
            });
            let target = $(this)
            if (target.hasClass('disabled')) return false

            target.addClass('disabled');

            let rating = $('input[name="rating"]').val()

            fetch('{{route('products.bulk_set_rating')}}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'fetch'
                },
                body: JSON.stringify({
                    _token: '{{csrf_token()}}',
                    rating,
                    ids: ids.join(',')
                })
            })
                .then(resp => resp.text())
                .then(res => {
                    if (res == 1) {
                        AIZ.plugins.notify('success', '{{translate('Operation Success')}}')
                        setTimeout(() => {
                            window.location.reload()
                        }, 500)
                    } else {
                        AIZ.plugins.notify('danger', '{{translate('Operation Fail')}}')
                        target.removeClass('disabled')
                    }

                })
                .catch(err => null).finally(() => {
                //target.removeClass('disabled')
            })

        })

    </script>
@endsection
